package com.ln.lnzw.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SnapHelper;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.github.rubensousa.gravitysnaphelper.GravitySnapHelper;
import com.ln.lnzw.R;
import com.ln.lnzw.activity.ServiceAppDetailActivity;
import com.ln.lnzw.activity.ServiceCatagoryListDetailsActivity;
import com.ln.lnzw.activity.ServiceSubscribeMoreActivity;
import com.ln.lnzw.adapter.MyGridViewAdpter;
import com.ln.lnzw.adapter.MyViewPagerAdapter;
import com.ln.lnzw.adapter.RecomToYouAdapter;
import com.ln.lnzw.adapter.ServiceSubscribeServiceAdapter;
import com.ln.lnzw.app.AppConstant;
import com.ln.lnzw.base.BaseFragment;
import com.ln.lnzw.bean.CategoryBean;
import com.ln.lnzw.bean.ProdctBean;
import com.ln.lnzw.bean.ServiceCategoryBean;
import com.ln.lnzw.bean.ServiceSubscribeServiceBean;
import com.ln.lnzw.bean.ServiceSubscribeServiceNetBean;
import com.ln.lnzw.bean.ServiceTopRecomBean;
import com.ln.lnzw.bean.ServiceTopRecomNetBean;
import com.ln.lnzw.bean.UniversalBean;
import com.ln.lnzw.event.SubscribeChangeEvent;
import com.ln.lnzw.net.HttpMethods;
import com.ln.lnzw.utils.StatusBarUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * 作者: wlt
 * 时间:2018-04-23 16:15
 * 类描述: 便民服务页面
 *
 */

public class ServiceFragment extends BaseFragment {

    @BindView(R.id.rv_tuijian)
    RecyclerView rvTuijian;
    Unbinder unbinder;
    @BindView(R.id.viewpager)
    ViewPager viewpager;
    @BindView(R.id.points)
    LinearLayout points;
    @BindView(R.id.fake_status_bar)
    ImageView fakeStatusBar;
    @BindView(R.id.tv_fuwu_more)
    TextView tvFuwuMore;
    @BindView(R.id.rv_dingyue)
    RecyclerView rvDingyue;
    /**
     * 顶部为你推荐的数据集合,暂用,假数据
     */
    private List<ServiceTopRecomBean> list = new ArrayList<>();
    /**
     * 推荐的adapter
     */
    private RecomToYouAdapter mAdapter;
    /**
     * 服务大类的数据集合,网络数据集合
     */
    private List<CategoryBean> listDatas = new ArrayList<>();
    /**
     * 小点图片集合
     */
    private ImageView[] ivPoints;
    /**
     * 总页数
     */
    private int totalPage;
    /**
     * 每页显示的最大的数量
     */
     int mPageSize = 8;
    /**
     *
     */
     List<View> viewPagerList;//GridView作为一个View对象添加到ViewPager集合中


    private static final String TAG = "ServiceFragment";
     String userName;//8dfda5b2-28fa-4cef-a455-2761946602cb
    /**
     * 底部订阅服务的数据列表
     */
    private List<ServiceSubscribeServiceBean> dingyueList = new ArrayList<>();
    /**
     * 底部订阅的数据适配器
     */
    private ServiceSubscribeServiceAdapter dingyueAdapter;

    public static ServiceFragment newInstance() {
        Bundle args = new Bundle();
        ServiceFragment fragment = new ServiceFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.servicefragment_activity, null);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        StatusBarUtils.statusBar(fakeStatusBar);
        EventBus.getDefault().register(this);
        rvTuijian.setLayoutManager(new LinearLayoutManager(activity, LinearLayout.HORIZONTAL, false));
        rvTuijian.setHasFixedSize(true);
        SnapHelper snapHelperStart = new GravitySnapHelper(Gravity.START);
        snapHelperStart.attachToRecyclerView(rvTuijian);
//        mAdapter = new ServiceTuiJianAdapter(R.layout.item_service_tuijian, list);
        mAdapter = new RecomToYouAdapter(R.layout.item_service_tuijian,list);
        rvTuijian.setAdapter(mAdapter);

        rvTuijian.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                Bundle bundle = new Bundle();
                bundle.putString("name",list.get(position).getAppName());
                bundle.putString("url",list.get(position).getAppMobileUrl());
                ActivityUtils.startActivity(bundle, ServiceAppDetailActivity.class);
            }
        });


        rvDingyue.setLayoutManager(new GridLayoutManager(activity, 2, LinearLayout.HORIZONTAL, false));
        SnapHelper snapHelperStart1 = new GravitySnapHelper(Gravity.START);
        snapHelperStart1.attachToRecyclerView(rvDingyue);
        dingyueAdapter = new ServiceSubscribeServiceAdapter(dingyueList);
        rvDingyue.setAdapter(dingyueAdapter);
        dingyueAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()){
                    case R.id.rl_subscribe_content://点击图标进详情,设置隐藏右上角删除键
                        refreshSelected(false);
                        Bundle bundle = new Bundle();
                        bundle.putString("name",dingyueList.get(position).getAppName());
                        bundle.putString("url",dingyueList.get(position).getAppMobileUrl());
                        ActivityUtils.startActivity(bundle, ServiceAppDetailActivity.class);
                        break;
                    case R.id.rl_subscribe_add://点击加号跳转订阅更多的栏目
                        refreshSelected(false);
                        ActivityUtils.startActivity(ServiceSubscribeMoreActivity.class);
                        break;
                    case R.id.iv_subscribe_delete://点击删除访问网络干掉这个栏目,然后重新获取
                        refreshSelected(false);
                        cancleSub(dingyueList.get(position).getAppUuid());
                        break;
                }
            }
        });
        dingyueAdapter.setOnItemChildLongClickListener(new BaseQuickAdapter.OnItemChildLongClickListener() {
            @Override
            public boolean onItemChildLongClick(BaseQuickAdapter adapter, View view, int position) {
                if (view.getId() == R.id.rl_subscribe_content){
                   refreshSelected(true);
                    return true;
                }
                return false;
            }
        });
        tvFuwuMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ActivityUtils.startActivity(ServiceSubscribeMoreActivity.class);
            }
        });
        getCategoryData();

    }

    /**
     * 抽取通用代码,替换成方法,用于刷新状态
     */
    private void refreshSelected(boolean isSelect) {
        for (int i = 0; i < dingyueList.size(); i++) {
            dingyueList.get(i).setSeclected(isSelect);
        }
        dingyueAdapter.setNewData(dingyueList);
        dingyueAdapter.notifyDataSetChanged();
    }

    /**
     *取消订阅的方法
     */
    private void cancleSub(String appUuid){
        userName = activity.spUtils.getString(AppConstant.USER_UID);
        HttpMethods.getInstanceCenter().info.cancleSub(userName,appUuid)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<UniversalBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(UniversalBean universalBean) {
                        Log.e(TAG, "onNext: 取消订阅"+universalBean.toString() );
                        if (universalBean.getMsg().equals("取消成功")){
                            ToastUtils.showShort("取消订阅成功");
                            getSubscribeList();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e(TAG, "onError:取消订阅失败 "+e.toString() );
                        ToastUtils.showShort("网络故障,取消订阅失败");
                    }

                    @Override
                    public void onComplete() {
                        EventBus.getDefault().post(new SubscribeChangeEvent("便民服务首页"));
                    }
                });
    }
    /**
     * 网络获取服务分类的数据
     */
    private void getCategoryData(){
        HttpMethods.getInstanceCenter().info.getServiceCategory()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ServiceCategoryBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(ServiceCategoryBean serviceCategoryBean) {
//                        Log.e(TAG, "onNext: "+serviceCategoryBean.toString() );
                        if (!listDatas.isEmpty()){listDatas.clear();}
                        if (null != serviceCategoryBean.getResult())
                        listDatas .addAll(serviceCategoryBean.getResult());
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e(TAG, "onError: "+e.toString() );
                    }

                    @Override
                    public void onComplete() {
                        initData();
                    }
                });
    }
    /**
     * 设置服务分类的数据以及调用网络获取顶部以及底部的数据
     */
    private void initData() {
        getTopList();

        initCategoryData();

        getSubscribeList();
    }

    private void initCategoryData() {
        // TODO 如果网络获取数据失败这里就会崩,所以写个try catch抓一下异常
        try{
            //总的页数向上取整
            totalPage = (int) Math.ceil(listDatas.size() * 1.0 / mPageSize);
        }catch (Exception  e){
            totalPage = 0;
        }

        Log.i("123", "initData: " + totalPage);
        viewPagerList = new ArrayList<View>();
        for ( int i = 0; i < totalPage; i++) {
            //每个页面都是inflate出一个新实例
            final GridView gridView = (GridView) View.inflate(activity, R.layout.item_gridview, null);
            gridView.setAdapter(new MyGridViewAdpter(activity, listDatas, i, mPageSize));
            //添加item点击监听
//            gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//                @Override
//                public void onItemClick(AdapterView<?> arg0, View arg1,
//                                        int position, long arg3) {
//                    Bundle bundle = new Bundle();
//
//                    bundle.putString("name",listDatas.get(position).getAppName());
//                    bundle.putString("serverKey",listDatas.get(position).getCateId());
//                    ActivityUtils.startActivity(bundle, ServiceCatagoryListDetailsActivity.class);
//
//                }
//            });
            //每一个GridView作为一个View对象添加到ViewPager集合中
            viewPagerList.add(gridView);
        }
        //设置ViewPager适配器
        viewpager.setAdapter(new MyViewPagerAdapter(viewPagerList));

        //添加小圆点
        ivPoints = new ImageView[totalPage];
        for (int i = 0; i < totalPage; i++) {
            //循坏加入点点图片组
            ivPoints[i] = new ImageView(activity);
            if (i == 0) {
                ivPoints[i].setImageResource(R.mipmap.fuwu_homeicon_switch01);
            } else {
                ivPoints[i].setImageResource(R.mipmap.fuwu_homeicon_switch02);
            }
            ivPoints[i].setPadding(8, 8, 2, 8);
            points.addView(ivPoints[i]);
        }
        //设置ViewPager的滑动监听，主要是设置点点的背景颜色的改变
        viewpager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                // TODO Auto-generated method stub
                //currentPage = position;
                for (int i = 0; i < totalPage; i++) {
                    if (i == position) {
                        ivPoints[i].setImageResource(R.mipmap.fuwu_homeicon_switch01);
                    } else {
                        ivPoints[i].setImageResource(R.mipmap.fuwu_homeicon_switch02);
                    }
                }
            }
        });
    }

    /**
     * 网络获取底部订阅服务的数据
     */
    private void getSubscribeList(){
        userName = activity.spUtils.getString(AppConstant.USER_UID);
        HttpMethods.getInstanceCenter().info.getServiceSubscribeList(userName)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ServiceSubscribeServiceNetBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(ServiceSubscribeServiceNetBean serviceSubscribeServiceNetBean) {
//                        Log.e(TAG, "onNext: 订阅列表"+serviceSubscribeServiceNetBean.toString());
                        if (!dingyueList.isEmpty()){dingyueList.clear();}
                        if (null != serviceSubscribeServiceNetBean.getResult())
                        dingyueList.addAll( serviceSubscribeServiceNetBean.getResult());
                        makeDingyueDatas();
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e(TAG, "onError: 获取订阅服务失败"+e.toString() );
                    }

                    @Override
                    public void onComplete() {

                        dingyueAdapter.setNewData(dingyueList);
                        dingyueAdapter.notifyDataSetChanged();
                    }
                });
    }

    /**
     * 处理订阅获取到的数据,增加一个加号
     * 当没有用户订阅的时候有一个加号
     * 有也是增加一个加号
     */
    private void makeDingyueDatas(){

            for (int i = 0; i < dingyueList.size(); i++) {
                dingyueList.get(i).itemType=ServiceSubscribeServiceBean.TYPE_NORMAL;
                dingyueList.get(i).setSeclected(false);
            }

            ServiceSubscribeServiceBean bean1 = new ServiceSubscribeServiceBean();
            bean1.itemType=ServiceSubscribeServiceBean.TYPE_ADD;
            dingyueList.add(bean1);

    }
    /**
     * 网络获取顶部推荐的数据
     */
    private void getTopList(){
        HttpMethods.getInstanceCenter().info.getTopRecomList()
                 .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ServiceTopRecomNetBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(ServiceTopRecomNetBean serviceTopRecomNetBean) {
//                        Log.e(TAG, "onNext: getTopList"+serviceTopRecomNetBean.toString() );
                        if (!list.isEmpty()){list.clear();}
                        if (null != serviceTopRecomNetBean.getResult())
                        list.addAll(serviceTopRecomNetBean.getResult()) ;
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e(TAG, "onError:getTopList "+e.toString() );
                    }

                    @Override
                    public void onComplete() {
                        mAdapter.setNewData(list);
                        mAdapter.notifyDataSetChanged();
                    }
                });
    }

    @Subscribe
    public void onMessageEvent(SubscribeChangeEvent event) {
        Log.i(TAG, "message is " + event.getRefresh());

        getSubscribeList();

    }
    @Subscribe
    public void onMessageEvent(String isLogin) {
        Log.i(TAG, "message is " + isLogin);

        getSubscribeList();

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        dispose();
        EventBus.getDefault().unregister(this);
    }

}
